package com.dong.common.io;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

public class AIOServerTest {
    public static void main(String[] args) throws IOException {
        AsynchronousServerSocketChannel serverSocketChannel = AsynchronousServerSocketChannel.open();
        serverSocketChannel.bind(new InetSocketAddress(8080));

        System.out.println("server is start");
        serverSocketChannel.accept(null, new CompletionHandler<AsynchronousSocketChannel, Object>() {

            @Override
            public void completed(AsynchronousSocketChannel socketChannel, Object attachment) {
                try {
                    System.out.println("accept new conn :"+socketChannel.getRemoteAddress());
                    while (true){
                        ByteBuffer allocate = ByteBuffer.allocate(1024);
                        Future<Integer> read = socketChannel.read(allocate);
                        if (read.get() >0){
                            allocate.flip();
                            byte[] bytes = new byte[allocate.remaining()];
                            // 将数据读入到byte数组中
                            allocate.get(bytes);

                            String content = new String(bytes, StandardCharsets.UTF_8);
                            // 换行符会当成另一条消息传过来
                            if (content.equals("\r\n")) {
                                continue;
                            }
                            System.out.println("receive msg: " + content);
                        }
                    }
                } catch (IOException | ExecutionException | InterruptedException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void failed(Throwable exc, Object attachment) {

            }
        });

        //阻塞主线程
        System.in.read();
    }
}
